package com.yilian.xlmusic.android.view;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.yilian.xlmusic.android.R;
import com.yilian.xlmusic.android.XlMusicActivity;
import com.yilian.xlmusic.android.base.BaseFragment;
import com.yilian.xlmusic.android.utils.TryLinearLayoutManager;
import com.yilian.xlmusic.android.utils.net.AppConstants;
import com.yilian.xlmusic.android.view.adapter.ItemRecycleViewAdapter;
import com.yilian.xlmusic.android.view.bean.GetCollectionBean;
import com.yilian.xlmusic.android.view.bean.MusicPlayerBean;
import com.yilian.xlmusic.android.view.bean.SharedViewModel;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import rxhttp.RxHttp;


public class CollectionMusicFragment extends BaseFragment {
    private SmartRefreshLayout refresh_view;
    private RecyclerView recycler_view;
    private int PAGE = 0;
    private int PER_PAGE = 15;
    private List<MusicPlayerBean.DataBean> listBeans = new ArrayList<>();
    private ItemRecycleViewAdapter itemRecycleViewAdapter2;
    private SharedViewModel model;
    private boolean first = true;
    @Override
    public int getLayoutResId() {
        return R.layout.fragment_collection_music;
    }

    @Override
    public void initBindInject(Object target, View view) {
        refresh_view = view.findViewById(R.id.refresh_layout);
        recycler_view = view.findViewById(R.id.recycler_view);

        refresh_view.setEnableRefresh(false);
        refresh_view.autoLoadMore();
        refresh_view.setEnableScrollContentWhenRefreshed(true);//是否在刷新完成时滚动列表显示新的内容 1.0.5
        refresh_view.setEnableLoadMoreWhenContentNotFull(false);//是否在列表不满一页时候开启上拉加载功能
        recycler_view.setLayoutManager(new TryLinearLayoutManager(mActivity));
        itemRecycleViewAdapter2 = new ItemRecycleViewAdapter(R.layout.music_player_item2, listBeans, true);
        recycler_view.setAdapter(itemRecycleViewAdapter2);
//        getCollectionResource();

        refresh_view.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                PAGE++;
                getCollectionResource();

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

            }
        });

        model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        model.getSelected().observe(getViewLifecycleOwner(), value -> {

            switch (value.getType()) {
                case 4:
                    PAGE = 0;
                    refresh_view.setEnableLoadMore(true);
                    if (first){
                        showDialog();
                        first = false;
                    }

                    if (itemRecycleViewAdapter2 != null) {
                        itemRecycleViewAdapter2.removeAllFooterView();
                    }
                    listBeans.clear();
                    getCollectionResource();
                    break;
            }

        });

    }

    private void getCollectionResource() {
        AppConstants.METHOD_NAME = "我的收藏列表：";
        RxHttp.get("/ylmusic-gateway/collection")
                .addHeader(AppConstants.ACCESS_TOKEN_KEY, AppConstants.ACCESS_TOKEN)
                .add("page", PAGE)
                .add("per_page", PER_PAGE)
                .add("category_id", 0)//category_id在0表示我的收藏，其他为音乐分类ID
                .asClass(GetCollectionBean.class)
                .observeOn(AndroidSchedulers.mainThread())  //主线程回调观察者
                .subscribe(callBackBean -> {
                    listBeans.addAll(callBackBean.getData().getList());
                    if (listBeans.size() > 0 && callBackBean.getData().getList().size() == 0 || listBeans.size()<PER_PAGE) {//下一页没有数据了
                        refresh_view.setEnableLoadMore(false);
                        if (listBeans.size() >= 7){
                            View inflate = View.inflate(mActivity, R.layout.none, null);
                            itemRecycleViewAdapter2.addFooterView(inflate);
                        }

                    }
                    if (itemRecycleViewAdapter2 != null) {
                        for (MusicPlayerBean.DataBean dataBean : listBeans) {
                            dataBean.setIs_play(false);
                        }
                        itemRecycleViewAdapter2.setList(listBeans);
                        itemRecycleViewAdapter2.notifyDataSetChanged();
                    }

                    //如果有音乐正在播放，就刷新下View
                    if (XlMusicActivity.mMediaPlayerUtils.isPlaying()) {
                        if (AppConstants.changeItems.size() > 0) {
                            //更新下正在播放歌曲的状态
                            for (MusicPlayerBean.DataBean dataBean : listBeans) {
                                if (dataBean.getId() == AppConstants.changeItems.get(0).getDataBean().getId()) {
                                    int index = listBeans.indexOf(dataBean);
                                    itemRecycleViewAdapter2.getData().get(index).setIs_play(true);
                                    itemRecycleViewAdapter2.getData().set(index, itemRecycleViewAdapter2.getData().get(index));
                                    itemRecycleViewAdapter2.notifyItemChanged(index, dataBean);
                                }
                            }
                        }
                    }
                    refresh_view.finishLoadMore();
                    if (isShowDialog()){
                        closeDialog();
                        refresh_view.setVisibility(View.VISIBLE);
                    }
                }, throwable -> {

                });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            //更新适配器的内容
            if (AppConstants.changeItems.size() > 0) {
                AppConstants.refreshView(AppConstants.changeItems.get(0));
            }
        }
    }


    @Override
    public void init(Bundle savedInstanceState) {

    }


}